<template>
  <van-form ref="createRegisterInputVO" label-width="85px" label-align="left" :scroll-to-error="true">
    <van-field
      label="头像"
      name="name"
      readonly
      required
      :clickable="!isCheckMode('imagePath')"
      input-align="right"
      right-icon="arrow"
      :style="{ 'line-height': createRegisterInputVO.imagePath ? '50px' : '24px' }"
      @click="openChangeLogo()"
    >
      <template #input>
        <show-avatar
          width="50px"
          height="50px"
          shape="circle"
          :src="getStaticFileUrl(createRegisterInputVO.imagePath)"
          @click="imagePreview(createRegisterInputVO.imagePath)"
        />
      </template>
    </van-field>
    <van-field
      v-model.trim="createRegisterInputVO.name"
      :readonly="isCheckMode('name')"
      label="姓名"
      name="name"
      placeholder="请输入姓名"
      required
      :rules="createRegisterInputVO_Rules.name"
    />
    <!-- 身份标签 -->
    <template v-if="isShowTag">
      <van-field
        label="身份标签"
        name="registerTags"
      >
        <template #input>
          <van-checkbox-group v-model.trim="createRegisterInputVO.registerTags" direction="horizontal">
            <van-checkbox
              v-for="item in registerTagList"
              :key="item.code"
              :name="item.code"
              shape="square"
              icon-size="16px"
            >{{ item.value }}</van-checkbox>
          </van-checkbox-group>
        </template>
      </van-field>
    </template>
    <van-field
      :value="findDictDataByCode('country', createRegisterInputVO.nationality).value"
      readonly
      :clickable="!isCheckMode('nationality')"
      label="国籍"
      name="nationality"
      right-icon="arrow"
      placeholder="请输入国籍"
      required
      :rules="createRegisterInputVO_Rules.nationality"
      @click="openSelectBox('nationality')"
    />
    <van-field
      :value="findDictDataByCode('nation', createRegisterInputVO.national).value"
      readonly
      :clickable="!isCheckMode('national')"
      name="national"
      label="民族"
      required
      right-icon="arrow"
      :rules="createRegisterInputVO_Rules.national"
      @click="openSelectBox('national')"
    />
    <van-field
      :value="findDictDataByCode('idCardType', createRegisterInputVO.idCardTypeCode).value"
      readonly
      :clickable="!isCheckMode('idCardTypeCode')"
      name="idCardTypeCode"
      label="证件类型"
      right-icon="arrow"
      required
      :rules="createRegisterInputVO_Rules.idCardTypeCode"
      @click="openSelectBox('idCardTypeCode')"
    />
    <van-field
      v-model.trim="createRegisterInputVO.idCardNumber"
      :readonly="isCheckMode('idCardNumber')"
      label="证件号码"
      required
      name="idCardNumber"
      :rules="createRegisterInputVO_Rules.idCardNumber"
      @input="computGenderAndBirth()"
    />
    <van-field
      :value="findDictDataByCode('dictGender', createRegisterInputVO.genderCode).value"
      readonly
      :clickable="!isCheckMode('genderCode')"
      name="genderCode"
      label="性别"
      required
      right-icon="arrow"
      :rules="createRegisterInputVO_Rules.genderCode"
      @click="openSelectBox('genderCode')"
    />
    <van-field
      :value="createRegisterInputVO.birthDate && createRegisterInputVO.birthDate.substring(0, 10)"
      readonly
      :clickable="!isCheckMode('birthDate')"
      name="birthDate"
      label="出生日期"
      required
      right-icon="arrow"
      :rules="createRegisterInputVO_Rules.birthDate"
      @click="openSelectDateTime()"
    />
    <van-field
      v-model.trim="createRegisterInputVO.phoneNumber"
      :readonly="isCheckMode('phoneNumber')"
      label="联系方式"
      name="phoneNumber"
    />
    <!-- 即将废弃，不在此组件内显示注释掉, ctkCode -> ctaMemberId -->
    <!-- <van-field
      v-model.trim="createRegisterInputVO.ctkCode"
      :readonly="isCheckMode('ctkCode')"
      label="中跆协会员号"
      name="phoneNumber"
      placeholder="请输入中跆协会员号"
    />
    <van-field
      v-model.trim="createRegisterInputVO.ptkCode"
      :readonly="isCheckMode('ptkCode')"
      label="省跆协会员号"
      name="phoneNumber"
      placeholder="请输入省跆协会员号"
    /> -->
    <van-field
      readonly
      :clickable="!isCheckMode('provinceCode')"
      name="provinceCode"
      label="所在地区"
      placeholder="所在地区"
      right-icon="arrow"
      :value="addressDataForCheck"
      @click="openAreaBox()"
    />
    <van-field
      v-model.trim="createRegisterInputVO.address"
      :readonly="isCheckMode('address')"
      rows="1"
      autosize
      label="详细地址"
      type="textarea"
      name="address"
      placeholder="请输入详细地址"
    />
    <van-field
      v-model.trim="createRegisterInputVO.emergencyContact"
      :readonly="isCheckMode('emergencyContact')"
      label="紧急联系人"
      name="emergencyContact"
      placeholder="请输入紧急联系人"
    />
    <van-field
      v-model.trim="createRegisterInputVO.emergencyContactPhoneNumber"
      :readonly="isCheckMode('emergencyContactPhoneNumber')"
      label="紧急联系方式"
      name="emergencyContactPhoneNumber"
      placeholder="请输入紧急联系方式"
      :rules="createRegisterInputVO_Rules.emergencyContactPhoneNumber"
    />
    <van-field
      :value="findDictDataByCode('dictRelationship', createRegisterInputVO.emergencyContactRelationship).value"
      readonly
      :clickable="!isCheckMode('emergencyContactRelationship')"
      name="emergencyContactRelationship"
      label="与本人关系"
      right-icon="arrow"
      @click="openSelectBox('emergencyContactRelationship')"
    />
    <!-- 实名认证 -->
    <template v-if="isShowIdCardImage">
      <van-field
        label="实名认证"
        readonly
        clickable
        input-align="right"
        right-icon="arrow"
        @click="openMemberImgDialog"
      >
        <template #input>
          <van-image
            v-if="createRegisterInputVO.idCardImage"
            width="48"
            height="30"
            class="gl_mr_5"
            :src="getStaticFileUrl(createRegisterInputVO.idCardImage)"
            @click="imagePreview(createRegisterInputVO.idCardImage)"
          />
          <van-image
            v-if="createRegisterInputVO.idCardBackImage"
            width="48"
            height="30"
            :src="getStaticFileUrl(createRegisterInputVO.idCardBackImage)"
            @click="imagePreview(createRegisterInputVO.idCardBackImage)"
          />
        </template>
      </van-field>
    </template>
    <!-- 下拉选择 -->
    <popup-select
      ref="popupSelect"
      :select-data="selectData"
      :default-code="selectDefaultCode"
      :value-key="valueKey"
      @onConfirm="confirmSelectBox"
    />
    <!-- 地区选择 -->
    <popup-area ref="popupArea" :default-area="defaultArea" @onConfirm="confirmAreaBox" />
    <!-- 时间选择 -->
    <popup-date-time ref="popupDateTime" :default-date-time="defaultDateTime" @onConfirm="confirmSelectDateTime" />
    <!-- 头像 -->
    <van-popup
      v-model="logoDialog"
      get-container="#app"
      position="right"
      :style="{ width: '100%', height: '100%' }"
    >
      <van-nav-bar>
        <template #left>
          <span @click="logoDialog = false">返回</span>
        </template>
      </van-nav-bar>
      <div class="upload_logo" align="center">
        <upload-file
          ref="logo"
          :action="baseUrl + '/api/upload/image'"
          accept=".jpg,.png,.jpeg"
          class-name="img_logo"
          :file-url="getStaticFileUrl(createRegisterInputVO.imagePath, 'imagePath')"
          @uploadSuccess="uploadSuccessLogo"
        >
          <span slot="uploadName" style="font-size: 14px;">点击上传头像</span>
        </upload-file>
      </div>
    </van-popup>
    <!-- 实名认证 - 身份证正面、身份证反面 -->
    <van-popup
      v-model="memberImgDialog"
      get-container="#app"
      position="right"
      :style="{ width: '100%', height: '100%' }"
    >
      <van-nav-bar>
        <template #left>
          <span @click="memberImgDialog = false">返回</span>
        </template>
      </van-nav-bar>
      <div class="gl_my_20" align="center">
        <upload-file
          ref="idCardImage"
          :action="baseUrl + '/api/upload/image'"
          accept=".jpg,.png,.jpeg"
          class-name="id_card"
          :file-url="getStaticFileUrl(createRegisterInputVO.idCardImage, 'idCardImage')"
          @uploadSuccess="uploadSuccessIdCardImage"
        >
          <span slot="uploadName" style="font-size: 14px;">点击上传证件照正面</span>
        </upload-file>
      </div>
      <div class="gl_my_20" align="center">
        <upload-file
          ref="idCardBackImage"
          :action="baseUrl + '/api/upload/image'"
          accept=".jpg,.png,.jpeg"
          class-name="id_card"
          :file-url="getStaticFileUrl(createRegisterInputVO.idCardBackImage, 'idCardBackImage')"
          @uploadSuccess="uploadSuccessIdCardBackImage"
        >
          <span slot="uploadName" style="font-size: 14px;">点击上传证件照反面</span>
        </upload-file>
      </div>
    </van-popup>
  </van-form>
</template>
<script>
import { mapState, mapActions } from 'vuex';
import { SiSTKWEventsManagementCreateRegisterWithTagsInput } from '@/lib/form/game/swaggerForm';
import { CreateRegisterInput_Rules } from '@/lib/validate/mobile/myCenter';
import PopupSelect from '@/viewMobile/components/PopupSelect';
import PopupArea from '@/viewMobile/components/PopupArea';
import PopupDateTime from '@/viewMobile/components/PopupDateTime';
import UploadFile from '@/viewMobile/components/UploadFile/index';
import { deepCopy, CopyData } from '@/lib';
import validator from '@/lib/validate/mobile/validator';
export default {
  components: {
    PopupSelect,
    PopupArea,
    PopupDateTime,
    UploadFile
  },
  props: {
    // 传入的个人信息数据
    userData: {
      type: Object,
      default() {
        return {};
      }
    },
    // 是否显示证件照正反面图片上传
    isShowIdCardImage: {
      type: Boolean,
      default: true
    },
    // 是否显示身份标签复选框组
    isShowTag: {
      type: Boolean,
      default: false
    },
    // 需要被过滤掉的身份标签列表，被过滤的标签不会显示：如 ['Athlete']
    filterTags: {
      type: Array,
      default() {
        return [];
      }
    },
    // 是否为查看模式，查看模式将把预设好的字段变为不可编辑状态
    isCheck: {
      type: Boolean,
      default: false
    },
    // 默认的查看模式以原型为基准：包括 name, nationality, national, idCardTypeCode, idCardNumber, genderCode, birthDate, addressData
    isDefaultCheck: {
      type: Boolean,
      default: false
    },
    // 查看模式字段集合，由调用组件传值决定，示例：['name']
    checkList: {
      type: Array,
      default() {
        return [];
      }
    }
  },
  data() {
    return {
      baseUrl: WEB_CONFIG.VUE_APP_STATIC_FILE_RUL,
      createRegisterInputVO: new SiSTKWEventsManagementCreateRegisterWithTagsInput(),
      createRegisterInputVO_Rules: new CreateRegisterInput_Rules(),
      createRegisterInputDTO: {},
      // 选择器
      selectData: [],
      selectDefaultCode: '',
      valueKey: 'value',
      defaultArea: [],
      defaultDateTime: '',
      /* 头像相关 */
      logoDialog: false,
      memberImgDialog: false
    };
  },
  computed: {
    ...mapState({
      dict: state => state.dict.dict,
      cache: state => state.dict.cache
    }),
    // 计算出可被选择的身份标签
    registerTagList () {
      let _returnList = [];
      if (this.isShowTag) {
        const _map = {};
        this.filterTags.forEach(item => {
          _map[item] = true;
        });
        _returnList = this.dict.registerTagType.filter(item => !(item.code in _map));
      } else {
        _returnList = [];
      }
      return _returnList;
    },
    // 显示为只可查看字段的map
    checkListMap () {
      if (this.isDefaultCheck) {
        return {
          name: true,
          nationality: true,
          national: true,
          idCardTypeCode: true,
          idCardNumber: true,
          genderCode: true,
          birthDate: true
        };
      } else {
        const _map = {};
        this.checkList.forEach(item => {
          _map[item] = true;
        });
        return _map;
      }
    },
    // 根据所在地区Code找到对应name
    addressDataForCheck () {
      const _provinceCode = this.createRegisterInputVO.provinceCode;
      const _cityCode = this.createRegisterInputVO.cityCode;
      const _countyCode = this.createRegisterInputVO.countyCode;
      let _provinceData;
      let _cityData;
      let _countyData;
      if (_provinceCode && this.cache.district) {
        _provinceData = this.cache.district.find(item => item.code === _provinceCode);
      }
      if (_cityCode && _provinceData) {
        _cityData = _provinceData.children.find(item => item.code === _cityCode);
      }
      if (_countyCode && _cityData) {
        _countyData = _cityData.children.find(item => item.code === _countyCode);
      }
      return `${_provinceData ? _provinceData.name : ''} ${_cityData ? _cityData.name : ''} ${_countyData ? _countyData.name : ''}`;
    }
  },
  watch: {
    userData: {
      immediate: true,
      deep: true,
      handler(val) {
        if (val) {
          this.init(val);
        }
      }
    }
  },
  created() {
    this.getDict();
    this.getDictByType(['district']);
    this.init();
  },
  methods: {
    ...mapActions({ getDict: 'dict/getDict', getDictByType: 'dict/getDictByType' }),
    // 字段是否只可查看处理函数
    isCheckMode(key) {
      // 如果 isCheck 存在则以 isCheck 为准
      if (this.isCheck) {
        return this.isCheck;
      } else {
        return (key in this.checkListMap);
      }
    },
    init() {
      this.createRegisterInputVO = new SiSTKWEventsManagementCreateRegisterWithTagsInput();
      this.createRegisterInputDTO = deepCopy(this.userData);
      CopyData(this.createRegisterInputDTO, this.createRegisterInputVO);
      this.handleChangeIdCardType(this.createRegisterInputVO.idCardTypeCode);
      // 处理所在地区显示
      this.createRegisterInputDTO.addressData = (this.createRegisterInputVO.provinceCode || '') + (this.createRegisterInputVO.cityCode || '') + (this.createRegisterInputVO.countyCode || '');
    },
    getInsideUserData() {
      return new Promise((resolve, reject) => {
        this.$refs.createRegisterInputVO.validate().then(() => {
          resolve(this.createRegisterInputVO);
        }).catch((err) => {
          console.log(err);
        });
      });
    },
    /* ===== select 选择器相关 ===== */
    openSelectBox(code) {
      if (this.isCheckMode(code)) return;
      // 解决某种情况下弹出框非本系统操作关闭之后无法打开
      this.$refs.popupSelect.close();
      this.selectBoxCode = code;
      this.valueKey = 'value';
      this.selectDefaultCode = this.createRegisterInputVO[code];
      switch (code) {
        // 民族
        case 'national':
          if (this.createRegisterInputVO.nationality === 'CHN') {
            this.selectData = this.dict ? this.dict.nation.filter(item => item.code !== '57') : [];
          } else {
            this.selectData = this.dict ? [{ code: '57', value: '其他' }] : [];
          }
          break;
        // 证件类型
        case 'idCardTypeCode':
          this.selectData = this.dict ? this.dict.idCardType : [];
          break;
        // 性别
        case 'genderCode':
          this.selectData = this.dict ? this.dict.dictGender : [];
          break;
        // 国籍
        case 'nationality':
          this.selectData = this.dict ? this.dict.country : [];
          break;
        // 与本人关系
        case 'emergencyContactRelationship':
          this.selectData = this.dict ? this.dict.dictRelationship : [];
          break;
        default:
          this.selectData = this.dict ? this.dict[code] : [];
          this.selectDefaultCode = this.createRegisterInputVO[code];
          break;
      }
      this.$refs.popupSelect.open();
    },
    confirmSelectBox(value) {
      switch (this.selectBoxCode) {
        // 证件类型
        case 'idCardTypeCode':
          this.createRegisterInputVO.idCardTypeCode = value.code;
          this.handleChangeIdCardType(value.code);
          break;
        case 'nationality':
          this.createRegisterInputVO[this.selectBoxCode] = value.code;
          this.createRegisterInputVO.national = '';
          break;
        default:
          this.createRegisterInputVO[this.selectBoxCode] = value.code;
          break;
      }
    },
    // 根据身份证号码计算性别及生日
    computGenderAndBirth () {
      const _idCardNum = this.createRegisterInputVO.idCardNumber;
      const _reg = /^[1-9][0-9]{5}(19|20)[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}([0-9]|x|X)$/;
      // 当证件类型为身份证 且 证件号码不为空 且 通过身份证校验时。自动设置性别和出生日期
      if (_reg.test(_idCardNum)) {
        const _genderNum = _idCardNum.slice(-2, -1);
        this.createRegisterInputVO.genderCode = _genderNum % 2 === 0 ? 'W' : 'M';
        this.createRegisterInputVO.birthDate = _idCardNum.slice(6, 10) + '-' + _idCardNum.slice(10, 12) + '-' + _idCardNum.slice(12, 14);
      }
    },
    openAreaBox() {
      if (this.isCheckMode('provinceCode')) return;
      const provinceCode = this.createRegisterInputVO.provinceCode;
      const cityCode = this.createRegisterInputVO.cityCode;
      const countyCode = this.createRegisterInputVO.countyCode;
      this.defaultArea = [provinceCode, cityCode, countyCode];
      this.$refs.popupArea.open();
    },
    confirmAreaBox(value) {
      this.createRegisterInputVO.provinceCode = value[0] && value[0].code;
      this.createRegisterInputVO.cityCode = value[1] && value[1].code;
      this.createRegisterInputVO.countyCode = value[2] && value[2].code;
      this.$refs.popupArea.close();
    },
    openSelectDateTime() {
      if (this.isCheckMode('birthDate')) return;
      this.defaultDateTime = this.createRegisterInputVO.birthDate && this.createRegisterInputVO.birthDate.substring(0, 10);
      this.$refs.popupDateTime.open();
    },
    confirmSelectDateTime(value) {
      this.createRegisterInputVO.birthDate = value;
    },
    // 打开修改头像框
    openChangeLogo() {
      if (this.isCheckMode('imagePath')) return;
      this.logoDialog = true;
    },
    uploadSuccessLogo(response) {
      this.$set(this.createRegisterInputVO, 'imagePath', response.tempUrl);
    },
    // 图片预览
    imagePreview(relativeUrl) {
      this.$imagePreview([this.getStaticFileUrl(relativeUrl)]);
      event.stopPropagation();
    },
    // 获取静态文件
    getStaticFileUrl(relativeUrl, code) {
      if (relativeUrl) {
        return WEB_CONFIG.VUE_APP_STATIC_FILE_RUL + relativeUrl;
      } else {
        return code ? '' : require('@/assets/images/face_default.png');
      }
    },
    // 根据code在相应字典中寻找数据
    findDictDataByCode (dictKey, code) {
      const _dict = this.dict[dictKey];
      if (_dict) {
        return _dict.find(item => item.code === code) || {};
      } else {
        console.log('findDictDataByCode -> findDictDataByCode: ' + dictKey + ', 未找到字典数据.');
        return {};
      }
    },
    // 证件类型发生变化
    handleChangeIdCardType(idCardType) {
      if (idCardType === 'IdCard') {
        this.createRegisterInputVO_Rules.idCardNumber = [
          {
            ...validator.required('请输入证件号码'),
            validator: validator.checkIdNumber,
            trigger: 'onBlur'
          }
        ];
      } else {
        this.createRegisterInputVO_Rules.idCardNumber = [validator.required('请输入证件号码')];
      }
    },
    // 打开修改实名认证 - 身份证正面、身份证反面
    openMemberImgDialog() {
      this.memberImgDialog = true;
    },
    uploadSuccessIdCardImage(response) {
      this.$set(this.createRegisterInputVO, 'idCardImage', response.tempUrl);
    },
    uploadSuccessIdCardBackImage(response) {
      this.$set(this.createRegisterInputVO, 'idCardBackImage', response.tempUrl);
    }
  }
};
</script>
<style>
.upload_logo {
  position: absolute;
  top: 40%;
  left: 50%;
  width: 100%;
  height: 200px;
  transform: translate(-50%, -50%);
}
</style>
